package com.netintech.common.utils;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.io.*;
import java.util.Base64;

@Component
public class FileDfsUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileDfsUtil.class);


    @Resource
    private FastFileStorageClient storageClient;

    /**
     * 上传文件
     */
    public String upload(MultipartFile multipartFile) throws Exception {
        String originalFilename = multipartFile.getOriginalFilename().
                substring(multipartFile.getOriginalFilename().
                        lastIndexOf(".") + 1);
        StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
                multipartFile.getInputStream(),
                multipartFile.getSize(), originalFilename, null);
        return storePath.getFullPath();
    }

    /**
     * 删除文件
     */
    public String deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return "fileUrl == >>文件路径为空...";
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
            return e.getMessage();
        }
        return "OK";
    }

    /**
     * 将base64图片字符串，上传
     * @param base64ImgStr base64图片字符串
     * @param imgFormat 图片格式
     * @param headUrl nginx或者tracker的ip+端口 如：http://172.16.1.73/fastdfs
     * @return 能够直接访问的图片url
     * @throws IOException
     */
    public String upload(String base64ImgStr,String imgFormat,String headUrl) throws IOException {
        if (StringUtils.isBlank(base64ImgStr)){
            return "";
        }
        byte[] bytes = Base64.getMimeDecoder().decode(base64ImgStr);
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        StorePath storePath = this.storageClient.uploadFile(in, in.available(), imgFormat, null);
        return headUrl+"/"+storePath.getFullPath();
    }

    /**
     * 上传文件
     */
    public String upload(File file, String headUrl) throws FileNotFoundException {
        String suffix = file.getName().substring(file.getName().lastIndexOf("."));
        StorePath storePath = this.storageClient.uploadFile(
                new FileInputStream(file),
                file.length(),suffix, null);
        return headUrl+"/"+storePath.getFullPath();
    }


}
